<?php
/**
 * Created by PhpStorm.
 * User: 86151
 * Date: 2024/3/6
 * Time: 10:23
 */

namespace app\api\controller;
use think\Config;
use think\Db;
use app\common\controller\Api;
use think\Exception;
use app\admin\model\Lianlians;
use app\admin\model\Auth;
use app\admin\model\Wxpay;
use app\admin\model\Index as IndexModel;
class Order extends api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function cd(){
        $res=[
            'order_amount'=>0.01,
            'order_sn'=>'5646465581122'
        ];
        $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/llpay";
        $Info = 'H5订单支付';
        $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info);
        dump($objectxml);die;
    }

    public function pay(){
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $order_id =$datainfo['id'];
        $order = Db::name('order')->where('id',$order_id)->find();
        $res = Wxpay::ordercx($order['order_no']);
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            $this->success("购买成功！~",$res['trade_state']);
        }else{
            $this->error("查询失败");//
        }
    }

    /**
     * 联联会员购买
     */
    public function llvipOrder(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $qinghai = 0; //会员五  青海类型
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        //会员特殊购买
        $zone_id = $datainfo['zone_id'];
        $class_id = $datainfo['class_id'];
        if($sanfang){  //三方兑换验证
            $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
            if ($sanfang_vip) {
                if($sanfang_vip['is_att'] == 3){
                    $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            } else {
                exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                if ($operator_vip['type'] == 5) {
                    $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }
        }
        $outOrderId = makeOrderNum();//本地订单
        $productSn = $datainfo['resource_id'];//商品编号
        $quantity = 1;//数量
        $customerName = $datainfo['name'];//用户姓名
        $customerPhoneNumber  = $datainfo['number'];//用户号码
        $idCard = $datainfo['idCard'];//身份证号码
        $travelDate = $datainfo['travelDate'];//购买时间
        if($userInfo['mobile'] != $customerPhoneNumber){
            $this->error("领取号码与注册号码不一致");
        }
        $itemlist = $datainfo['itemlist'];//规格id
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('ll_itemlist')->where('itemId',$itemlist)->find();
        $lianlian = new Lianlians;
        $res = $lianlian->valid($outOrderId,$productSn,$itemlist,$goods['channelPrice'],$customerName,$customerPhoneNumber,$quantity,$goods['salePrice'],$idCard,$travelDate);
        if($res['code'] == 200){
            if($zone_id) {
                $exchange_goods = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $productSn)->find();
                $original_price_cent = $exchange_goods['fsj'];//原价
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
            }
            $params = [
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$res['data']['encryptedData']['validToken'],
                'order_no'=>$outOrderId,
                'type'=>10,//联联商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$quantity,
                'title'=>$goods['subTitle'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'biz_order_id'=>$res['data']['encryptedData']['thirdOrderId'],
                'zone_id'=> $zone_id,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'class_id'=> $class_id,
                'from'=>2,
                'qing_id'=>$qinghai,
                'exchange_code'=>'',
                'idcard'=>$idCard,
                'channelPrice'=>$goods['channelPrice'],
                'llthirdSalePrice'=>$goods['salePrice'],
                'llname'=>$customerName,
                'llgg_id'=>$itemlist,
                'price'=>round($goods['channelPrice'] * $quantity /100,2)
            ];
            if($travelDate){
                $params['time'] = $travelDate;
            }
            $params['discount_amount'] = $original_price_cent - $activity_price_cent;
            $amount =$activity_price_cent;
            $params['amount'] = $amount;
            $id = Db::name("order")->insertGetId($params);
            if($id) {
                //---微信支付---
                if ($amount > 0) {
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$outOrderId
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/llpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error('创建订单失败!');
            }
        }else{
            $this->error($res['message']);
        }
    }

    /**
     * 联联兑换
     */
    public function llexchange(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $qinghai  = 0; //青海类型
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        //会员特殊购买
        $zone_id = $datainfo['zone_id'];
        $class_id = $datainfo['class_id'];
        $outOrderId = makeOrderNum();//本地订单
        $productSn = $datainfo['resource_id'];//商品编号
        $quantity = 1;//数量
        $customerName = $datainfo['name'];//用户姓名
        $customerPhoneNumber  = $datainfo['number'];//用户号码
        $idCard = $datainfo['idCard'];//身份证号码
        $travelDate = $datainfo['travelDate'];//购买时间
        if($userInfo['mobile'] != $customerPhoneNumber){
            $this->error("领取号码与注册号码不一致");
        }
        $itemlist = $datainfo['itemlist'];//规格id
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('ll_itemlist')->where('itemId',$itemlist)->find();
        if($zone_id) {
            $exchange_goods = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $productSn)->find();
            $activity_price_cent = $exchange_goods['vip_money'];//会员价价
        }
        if($activity_price_cent>0){
            $this->error("流程错误");exit;
        }
        $lianlian = new Lianlians;
        $res = $lianlian->valid($outOrderId,$productSn,$itemlist,$goods['channelPrice'],$customerName,$customerPhoneNumber,$quantity,$goods['salePrice'],$idCard,$travelDate);
        if($res['code'] == 200){
            $params = [
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$res['data']['encryptedData']['validToken'],
                'order_no'=>$outOrderId,
                'type'=>10,//联联商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'num'=>$quantity,
                'title'=>$goods['subTitle'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'biz_order_id'=>$res['data']['encryptedData']['thirdOrderId'],
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'exchange_code'=>'',
                'idcard'=>$idCard,
                'channelPrice'=>$goods['channelPrice'],
                'llthirdSalePrice'=>$goods['salePrice'],
                'llname'=>$customerName,
                'llgg_id'=>$itemlist,
                'price'=>round($goods['channelPrice'] * $quantity /100,2)
            ];
            if($travelDate){
                $params['time'] = $travelDate;
            }
            $amount = $goods['salePrice'];
            $params['discount_amount'] = round($amount/100,2);
            $params['amount'] = 0;
            $id = 0;
            if($sanfang){  //三方兑换验证
                Db::startTrans();
                try {
                    $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
                    if ($sanfang_vip) {
                        if($sanfang_vip['is_att'] == 3){
                            $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id',$zone_id)->where('is_do',0)->where('end_time','>',time())->lock(true)->find();
                            if(!$qinghao){
                                Db::rollback();
                                exit(json_encode(array('code' =>0, 'msg' =>'会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id',$qinghao['id'])->update(['is_do'=>1]);
                            $qinghai = $qinghao['id'];
                        }
                    } else {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
                    }
                    $params['from'] = 2;
                    $id = Db::name("order")->insertGetId($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
            }else {
                if ($zone_id) {
                    if (!$userInfo['vip_id']) {
                        $this->error("您还不是会员,请先购买会员吧！~");
                        exit;
                    }
                    Db::startTrans();
                    try {
                        $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                        if ($operator_vip['type'] == 5) {
                            $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->lock(true)->find();
                            if (!$qinghao) {
                                Db::rollback();
                                exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id', $qinghao['id'])->update(['is_do' => 1]);
                            $qinghai = $qinghao['id'];
                        }
                        $params['from'] = 2;
                        $id = Db::name("order")->insertGetId($params);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' => 0, 'msg' => $e), JSON_UNESCAPED_UNICODE));
                    }
                }
            }
            if($id) {
                $order = Db::name("order")->where('id', $id)->find();
                $res =  $lianlian->creates($order['order_no'],$order['outer_order_id'],$order['resource_id'],$order['llgg_id'],$goods['channelPrice'],$order['llname'],$order['user_mobile'],$order['num'],$order['llthirdSalePrice'],$idCard,$travelDate);
                if($res['code'] == 200){
                    Db::startTrans();
                    try {
                        $orderList = json_encode($res['data']['encryptedData']['orderList']);
                        Db::name("order")->where(['id' => $id])->update([
                            'status' => 2,
                            'orderList' => $orderList
                        ]);
                        Db::name('goods')->where('item_id', $order['resource_id'])->setInc('total_sales');
                        Db::name('goods')->where('item_id', $order['resource_id'])->setDec('stock');
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->success("购买成功！~",$strArr);
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    if($qinghai >0){
                        Db::name('qinghao')->where('id',$qinghai)->update(['is_do'=>0]);
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }
    }

    /**
     * 联联正常购买
     */
    public function llorder(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $outOrderId = makeOrderNum();//本地订单
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $operator = Db::name('operator')->where('name',$userInfo['operator'])->field('id')->find();
        if($operator){
            $operator_id = $operator['id'];
        }else{
            $operator_id = 1;
        }
        $productSn = $datainfo['resource_id'];//商品编号
        $itemlist =  $datainfo['itemlist'];//规格id
        $quantity = 1;//数量
        $customerName = $datainfo['name'];//用户姓名
        $customerPhoneNumber  = $datainfo['number'];//用户号码
        $idCard = $datainfo['idCard'];//身份证号码
        $travelDate = $datainfo['travelDate'];//购买时间
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('ll_itemlist')->where('itemId',$itemlist)->find();
        $lianlian = new Lianlians;
        $res = $lianlian->valid($outOrderId,$productSn,$itemlist,$goods['channelPrice'],$customerName,$customerPhoneNumber,$quantity,$goods['salePrice'],$idCard,$travelDate);
        if($res['code'] != 200){
            $this->error($res['message']);
        }else{
            $original_price_cent = $goods['originPrice'] * $quantity;//原价
            $activity_price_cent = $goods['salePrice'] * $quantity;//活动价
            $params = [
                'operator_id'=>$operator_id,
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$res['data']['encryptedData']['validToken'],
                'order_no'=>$outOrderId,
                'type'=>10,//联联商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$quantity,
                'title'=>$goods['subTitle'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'biz_order_id'=>$res['data']['encryptedData']['thirdOrderId'],
                'idcard'=>$idCard,
                'channelPrice'=>$goods['channelPrice'],
                'llthirdSalePrice'=>$goods['salePrice'],
                'llname'=>$customerName,
                'llgg_id'=>$itemlist,
                'price'=> round($goods['channelPrice'] * $quantity /100,2),//成本价格
            ];
            if($travelDate){
                $params['time'] = $travelDate;
            }
            //是会员的话，打折
            $amount = $activity_price_cent;
            $amount = round($amount / 100, 2);//转为正常价格,因为数据库里存的是分
            $params['discount_amount'] = round($original_price_cent / 100, 2) - $amount;
            $params['amount'] = $amount;
            //阿里订单创建并返回支付参数
            $id = Db::name("order")->insertGetId($params);
            if($id){
                //---微信支付---
                if($amount>0){
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$outOrderId
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/llpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error('创建订单失败!');
            }
        }
    }
    /**
     * 联联退款
     */
    public function llrefund(){
        $order_id =  input('order_id');
        $reason = input("reason");//退款原因
        if(!$order_id){
            $this->error('参数不全');
        }
        $order = Db::name("order")->where('id',$order_id)->find();
        $ll_codeorder = Db::name('ll_codeorder')->where('thirdOrderId',$order['order_no'])->find();
        $codeList = json_decode($ll_codeorder['codeList'],true);
        if($order['from']==2){
            //兑换的订单不作退还
            $this->error("该订单属于会员专享兑换权益，不支持退换，详情请咨询在线客服：4008772758");
        }
        $lianlian = new Lianlians;
        $res = $lianlian->refund($ll_codeorder['channelOrderId'],$codeList[0]['orderId']);
        if($res == 0){
            if($order['amount']>0){
                Wxpay::doRefund($order['amount'],$order['amount'],$order['order_no'],$order['transaction_id'],$reason);
            }
            Db::startTrans();
            try {
                Db::name('order')->where('id',$order_id)->update(['status'=>5,'rund_time'=>time(),'rund_info'=>$reason]);
                Db::name('voucher')->where('order_id',$order_id)->update(['voucher_status'=>'CANCELED']);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
            }
            $this->success('退款成功');
        }else{
            $this->error('退款失败请联系客服');
        }
    }
}